package com.rc.saas.tenant.controller.elec;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.mq.MqConfig;
import com.rc.saas.tenant.common.mq.MqProducer;
import com.rc.saas.tenant.common.mq.RabbitListenerConstant;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.DateUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.utils.TimeUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadComponent;
import com.rc.saas.tenant.component.UploadImg;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.area.PlatformArea;
import com.rc.saas.tenant.model.area.PlatformCity;
import com.rc.saas.tenant.model.area.PlatformProvince;
import com.rc.saas.tenant.model.device.RcLabel;
import com.rc.saas.tenant.model.elec.*;
import com.rc.saas.tenant.model.hlht.HlhtTenantOpen;
import com.rc.saas.tenant.model.hlht.HlhtTenantOpenExample;
import com.rc.saas.tenant.model.hlht.HlhtTenantOpenPrice;
import com.rc.saas.tenant.model.hlht.HlhtTenantOpenPriceExample;
import com.rc.saas.tenant.model.operator.*;
import com.rc.saas.tenant.model.tenant.*;
import com.rc.saas.tenant.search.elec.ElecPileSearch;
import com.rc.saas.tenant.search.elec.ElecSationSearch;
import com.rc.saas.tenant.search.elec.ElecStationPriceSearch;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.service.area.PlatformAreaService;
import com.rc.saas.tenant.service.elec.*;
import com.rc.saas.tenant.service.hlht.HlhtTenantOpenPriceService;
import com.rc.saas.tenant.service.hlht.HlhtTenantOpenService;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.service.operator.TenantOperatorService;
import com.rc.saas.tenant.service.operator.TenantOperatorStationService;
import com.rc.saas.tenant.service.tenant.*;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.elec.*;
import com.rc.saas.tenant.vo.log.TenantOperateLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


/**
 * @author frog
 * @data 2019/10/16
 */
@Controller
@RequestMapping("/elecStation")
public class ElecStationController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(ElecStationController.class);

    @Autowired
    private UploadImg uploadImg;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private PlatformAreaService areaService;

    @Autowired
    private ElecStationPriceService elecStationPriceService;

    @Autowired
    private TenantService tenantService;

    @Autowired
    private TenantManufacturerService tenantManufacturerService;

    @Autowired
    private TenantOperatorService tenantOperatorService;

    @Autowired
    private ElecStationOutService elecStationOutService;

    @Autowired
    private TenantOperatorStationService tenantOperatorStationService;

    @Autowired
    private HlhtTenantOpenService hlhtTenantOpenService;

    @Autowired
    private HlhtTenantOpenPriceService hlhtTenantOpenPriceService;

    @Autowired
    private TenantSettingService tenantSettingService;

    @Autowired
    private TenantCompanyInfoService tenantCompanyInfoService;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private RcOperatorService operatorService;

    @Autowired
    private ElecLabelService elecLabelService;

    @Autowired
    private UploadComponent uploadComponent;

    @Autowired
    private ElecPileService elecPileService;
    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private RcOperatorService rcOperatorService;
    @Autowired
    private TenantRoleService tenantRoleService;

    /**
     * 跳转桩群页面
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String elecStationPage(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<TenantCompanyInfo> tenantCompanyInfos = tenantCompanyInfoService.listByTenantCode(user.getTenantCode());
        model.addAttribute("tenantCompanyInfos", tenantCompanyInfos);
        return "/templates/elec/elecStation";
    }

    /**
     * 返回桩群列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listStation", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listStation(ElecSationSearch elecSationSearchVo) {
        TenantUser user = ShiroUtils.getSessionUser();
        elecSationSearchVo.setLoginName(user.getLoginName());
        //默认其他省为10000
        if ("10000".equals(elecSationSearchVo.getAreaId())) {
            String provinceId = elecStationService.selectMostProvinceId(user.getTenantCode());
            elecSationSearchVo.setAreaId(null);
            elecSationSearchVo.setProvinceId(provinceId);
        }

      /*  //是否加盟商
        if(user.getMobile()!=null){
            RcOperatorExample rcOperatorExample=new RcOperatorExample();
            rcOperatorExample.createCriteria().andPhoneEqualTo(user.getMobile());
            rcOperatorExample.setOrderByClause("operator_id desc");
            RcOperator rcOperator=rcOperatorService.selectByExample(rcOperatorExample).stream().findFirst().orElseGet(()->null);
            if(rcOperator!=null){
                elecSationSearchVo.setOperatorId(rcOperator.getOperatorId());
            }
            if(user.getTenantRoleId()!=null){
                TenantRole tenantRole=tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
                if(tenantRole.getDataAuth()!=null&&!"111".equals(tenantRole.getDataAuth())){
                    elecSationSearchVo.setDataAuth(tenantRole.getDataAuth());
                }
            }
        }
*/

        PageInfo<ElecStationResult> pageInfo = elecStationService.listPageByCondition(elecSationSearchVo);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 返回桩群列表数据
     *
     * @return
     */
    @RequestMapping(value = "/statisticsStationNum", method = RequestMethod.GET)
    @ResponseBody
    public StatisticsStationNum statisticsStationNum(ElecSationSearch elecSationSearchVo) {
        TenantUser user = ShiroUtils.getSessionUser();
        elecSationSearchVo.setLoginName(user.getLoginName());
        //默认其他省为10000
        if ("10000".equals(elecSationSearchVo.getAreaId())) {
            String provinceId = elecStationService.selectMostProvinceId(user.getTenantCode());
            elecSationSearchVo.setAreaId(null);
            elecSationSearchVo.setProvinceId(provinceId);
        }
        StatisticsStationNum info = elecStationService.getStatisticsStationNum(elecSationSearchVo);
        return info;
    }

    /**
     * 导出站点列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(ElecSationSearch elecSationSearchVo, HttpServletResponse response) {
        try {
            //默认其他省为10000
            if ("10000".equals(elecSationSearchVo.getAreaId())) {
                TenantUser user = ShiroUtils.getSessionUser();
                String provinceId = elecStationService.selectMostProvinceId(user.getTenantCode());
                elecSationSearchVo.setAreaId(null);
                elecSationSearchVo.setProvinceId(provinceId);
            }
            ExportUtils.setDefaultPaging(elecSationSearchVo);
            PageInfo<ElecStationResult> pageInfo = elecStationService.listPageByCondition(elecSationSearchVo);
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("站点列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ElecStationResult.class).sheet("站点列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出站点列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /**
     * 跳转分销商桩群页面
     *
     * @return
     */
    @RequestMapping(value = "/operator/index", method = RequestMethod.GET)
    public String operatorElecStationPage() {
        return "/templates/elec/operatorElecStation";
    }

    /**
     * 返回分销商桩群列表数据
     *
     * @return
     */
    @RequestMapping(value = "/operator/listStation", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo operatorlistStation(ElecSationSearch elecSationSearchVo) {
        TenantUser user = ShiroUtils.getSessionUser();
        //默认其他省为10000
        if ("10000".equals(elecSationSearchVo.getAreaId())) {
            String provinceId = elecStationService.selectMostProvinceId(user.getTenantCode());
            elecSationSearchVo.setAreaId(null);
            elecSationSearchVo.setProvinceId(provinceId);
        }
        PageInfo<ElecStationResult> pageInfo = elecStationService.listPageOperatorElecStaion(elecSationSearchVo);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转分销商桩页面
     *
     * @return
     */
    @RequestMapping(value = "/operator/operatorPileListPage/{elecStationId}", method = RequestMethod.GET)
    public String operatorPileListPage(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/operatorElecPileByStation";
    }

    /**
     * 根据运营商所在的地区提供查询
     */
    @RequestMapping("/selectByArea")
    @ResponseBody
    public TResponse selectByArea() {
        TenantUser user = ShiroUtils.getSessionUser();
        String provinceId = elecStationService.selectMostProvinceId(user.getTenantCode());
        PlatformProvince platformProvince = elecStationService.selectAllAreaByProvinceId(provinceId);
        return TResponse.SUCCESS_DATA(platformProvince);
    }


    /**
     * 根据城市id获取区域
     *
     * @param cityId
     * @return
     */
    @RequestMapping(value = "/getArea", method = RequestMethod.GET)
    @ResponseBody
    public TResponse getArea(String cityId) {
        List<PlatformArea> areas = areaService.listAreaByCityId(cityId);
        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put(areas);
        return tResponse;
    }

    /**
     * 根据省id获取市
     *
     * @param provinceId
     * @return
     */
    @RequestMapping(value = "/getCity", method = RequestMethod.GET)
    @ResponseBody
    public TResponse getCity(String provinceId) {
        List<PlatformCity> cities = areaService.listCityByProvinceId(provinceId);
        TResponse tResponse = TResponse.SUCCESS();
        tResponse.put(cities);
        return tResponse;
    }


    /**
     * 跳转编辑桩群
     *
     * @return
     */
    @RequestMapping(value = "/editStation/{elecStationId}", method = RequestMethod.GET)
    public String editStation(@PathVariable("elecStationId") Long elecStationId, Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<TenantOperator> tenantOperators = tenantOperatorService.listOperatorByTenantCode(user.getTenantCode());
        model.addAttribute("tenantOperators", tenantOperators);
        List<PlatformProvince> provinces = areaService.listAllProvince();
        model.addAttribute("provinces", provinces);
        ElecStationAndCityName elecStation = elecStationService.selectStationAndCity(elecStationId);
        Date operateStartTime = elecStation.getOperateStartTime();
        if (operateStartTime != null) {
            elecStation.setOperateStartDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(operateStartTime));
        }
        List<TenantCompanyInfo> tenantCompanyInfos = tenantCompanyInfoService.listByTenantCode(user.getTenantCode());
        model.addAttribute("tenantCompanyInfos", tenantCompanyInfos);
        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
        model.addAttribute("elecStation", elecStation);
        List<RcOperator> operators = operatorService.loadOperator(user.getLoginName());
        model.addAttribute("operators", operators);
        List<RcLabel> label = elecLabelService.loadLabel();
        model.addAttribute("labels", label);
        return "/templates/elec/editElecStation";
    }

    /**
     * 跳转增加充电站
     *
     * @return
     */
    @RequestMapping(value = "/addStation", method = RequestMethod.GET)
    public String addStation(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<TenantCompanyInfo> tenantCompanyInfos = tenantCompanyInfoService.listByTenantCode(user.getTenantCode());
        model.addAttribute("tenantCompanyInfos", tenantCompanyInfos);
        List<TenantOperator> tenantOperators = tenantOperatorService.listOperatorByTenantCode(user.getTenantCode());
        model.addAttribute("tenantOperators", tenantOperators);
        List<PlatformProvince> provinces = areaService.listAllProvince();
        model.addAttribute("provinces", provinces);
        List<RcOperator> operators = operatorService.loadOperator(user.getLoginName());
        model.addAttribute("operators", operators);
        List<RcLabel> label = elecLabelService.loadLabel();
        /*List<RcLabel> label =new ArrayList<>();
        RcLabel labelInfo = new RcLabel();
        labelInfo.setLabelId(1l);
        labelInfo.setLabelName("asad");
        label.add(labelInfo);*/
        model.addAttribute("label", label);
        return "/templates/elec/addElecStation";
    }


    /**
     * 跳转桩群详情
     *
     * @return
     */
    @RequestMapping(value = "/detailStation/{elecStationId}", method = RequestMethod.GET)
    public String detailStation(@PathVariable("elecStationId") Long elecStationId, Model model) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        List<PlatformProvince> provinces = areaService.listAllProvince();
        ElecStationAndCityName elecStation = elecStationService.selectStationAndCity(elecStationId);
        Date operateStartTime = elecStation.getOperateStartTime();
        if (operateStartTime != null) {
            elecStation.setOperateStartDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(operateStartTime));
        }
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(elecStation.getTenantOperatorCode());
        List<TenantCompanyInfo> tenantCompanyInfos = tenantCompanyInfoService.listByTenantCode(tenantUser.getTenantCode());
        RcOperator operator = operatorService.selectByPrimaryKey(elecStation.getOperatorId());
        model.addAttribute("tenantCompanyInfos", tenantCompanyInfos);
        model.addAttribute("tenantOperator", tenantOperator);
        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
        model.addAttribute("provinces", provinces);
        model.addAttribute("elecStation", elecStation);
        model.addAttribute("operator", operator);
        return "/templates/elec/detailStation";
    }

    /**
     * 跳转桩列表
     *
     * @return
     */
    @RequestMapping(value = "/elecPileSub/{elecStationId}", method = RequestMethod.GET)
    public String elecPileSub(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/elecPile";
    }


    /**
     * 跳转枪列表
     *
     * @return
     */
    @RequestMapping(value = "/elecGunSub/{elecStationId}", method = RequestMethod.GET)
    public String elecGunSub(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/elecGun";
    }


    /**
     * 桩群上线或者下线
     */
    @ResponseBody
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    public TResponse updateStatus(Long elecStationId) {
        try {
            elecStationService.updateStatus(elecStationId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("更新桩群状态失败", e);
            return TResponse.FAIL("更新状态失败");
        }
    }

    /**
     * 配置占桩费
     */
    @ResponseBody
    @RequestMapping(value = "/updateOccupy", method = RequestMethod.POST)
    public TResponse updateOccupy(Long id, String occupyStatus, Integer occupyFree, String occupyPrice) {

        try {
            ElecStation esInfo = elecStationService.selectByPrimaryKey(id);
            if (esInfo != null) {
                esInfo.setOccupyStatus(occupyStatus);
                esInfo.setOccupyFree(occupyFree);
                esInfo.setOccupyPrice(new BigDecimal(occupyPrice));
                esInfo.setLastUpdatedTime(new Date());
                elecStationService.updateByPrimaryKey(esInfo);
                logger.info("配置占用费成功,对应站点:{},对应状态:{},对应单价:{},对应免费时长:{}", esInfo.getStationName(), occupyStatus, occupyPrice, occupyFree);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("更新桩群状态失败", e);
            return TResponse.FAIL("更新状态失败");
        }
    }

    /**
     * 保存编辑桩群
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateElecStation", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateElecStation(ElecStation elecStation,
                                             @RequestParam(value = "file1", required = false) MultipartFile file1,
                                             @RequestParam(value = "file2", required = false) MultipartFile file2,
                                             @RequestParam(value = "file3", required = false) MultipartFile file3,
                                             @RequestParam(value = "file4", required = false) MultipartFile file4,
                                             @RequestParam(value = "file5", required = false) MultipartFile file5) {

        TenantUser user = ShiroUtils.getSessionUser();

        if (!BeanUtil.isValid(elecStation.getStationName())) {
            return TResponse.FAIL("请输入正确的参数");
        }

        elecStation.setTenantCode(user.getTenantCode());
        Tenant tenant = tenantService.selectByTenantCode(user.getTenantCode());

        try {
            if (file1 != null && file1.getSize() != 0 && file1.getContentType().contains("image")) {
                String imgUrl = uploadComponent.uploadFile(user.getTenantCode(), file1);
                elecStation.setStationImg1(imgUrl);
            }
            if (file2 != null && file2.getSize() != 0 && file2.getContentType().contains("image")) {
                String imgUrl2 = uploadComponent.uploadFile(user.getTenantCode(), file2);
                elecStation.setStationImg2(imgUrl2);
            }
            if (file3 != null && file3.getSize() != 0 && file3.getContentType().contains("image")) {
                String imgUrl3 = uploadComponent.uploadFile(user.getTenantCode(), file3);
                elecStation.setStationImg3(imgUrl3);
            }
            if (file4 != null && file4.getSize() != 0 && file4.getContentType().contains("image")) {
                String imgUrl4 = uploadComponent.uploadFile(user.getTenantCode(), file4);
                elecStation.setStationImg4(imgUrl4);
            }
            if (file5 != null && file5.getSize() != 0 && file5.getContentType().contains("image")) {
                String imgUrl5 = uploadComponent.uploadFile(user.getTenantCode(), file5);
                elecStation.setStationImg5(imgUrl5);
            }
             /*if (file1.getSize() != 0) {

                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file1);
                if (tResponse.getStatus() == 200) {
                    elecStation.setStationImg1((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }


            if (file2.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file2);
                if (tResponse.getStatus() == 200) {
                    elecStation.setStationImg2((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (file3.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file3);
                if (tResponse.getStatus() == 200) {
                    elecStation.setStationImg3((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (file4.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file4);
                if (tResponse.getStatus() == 200) {
                    elecStation.setStationImg4((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (file5.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file5);
                if (tResponse.getStatus() == 200) {
                    elecStation.setStationImg5((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }*/
            if (org.apache.commons.lang.StringUtils.equals(DateUtil.format(
                    elecStation.getOperateStartTime(), DateUtil.DATE_FORMAT), DateUtil.format(new Date(), DateUtil.DATE_FORMAT))) {
                elecStation.setOperateStatus("1");
            } else {
                elecStation.setOperateStatus("0");
            }

            if (elecStation.getElecStationId() != null) {
              /*  if (StringUtils.isNotBlank(elecStation.getLabelIds())){
                    String labelNames = elecLabelService.getLabelNames(StringUtil.stringArray2Strin(elecStation.getLabelIds().split(",")));
                    elecStation.setStationFlag(labelNames);
                }*/
                elecStationService.updateByPrimaryKeySelective(elecStation);
                elecPileService.updateOperatorBySId(elecStation);
                elecGunService.updateOperatorBySId(elecStation);
            } else {
                if (StringUtil.isNotBlank(tenant.getElecServerDomain()) && tenant.getElecServerSpliter() != null) {
                    elecStation.setElecServerDomain(tenant.getElecServerDomain());
                    elecStation.setElecServerSpliter(tenant.getElecServerSpliter());
                } else {
                    elecStation.setElecServerDomain("STD_DOMAIN");
                    elecStation.setElecServerSpliter(0);
                }
                String stationNo = null;
                //查询最后一个充电站编码顺序
                ElecStation stationInfo = elecStationService.selectLaststationNo();
                /*String stationNo = elecStationService.generateStationNo(tenant);*/
                if (stationInfo == null) {
                    stationNo = elecStation.getCityId().substring(0, elecStation.getCityId().length() - 2) + "0001";
                } else {
                    stationNo = StringUtil.newNo(stationInfo.getStationNo(), 4);
                }
                ElecStationExample example = new ElecStationExample();
                example.createCriteria().andStationNoEqualTo(stationNo);
                List<ElecStation> elecStations = elecStationService.selectByExample(example);
                if (!CollectionUtils.isEmpty(elecStations)) {
                    return TResponse.FAIL("充电站编号生成重复,请联系研发");
                }
                /*if (StringUtils.isNotBlank(elecStation.getLabelIds())){
                    String labelNames = elecLabelService.getLabelNames(StringUtil.stringArray2Strin(elecStation.getLabelIds().split(",")));
                    elecStation.setStationFlag(labelNames);
                }*/
                elecStation.setStationNo(stationNo);
                elecStation.setCreatedBy(user.getLoginName());
                elecStation.setCreatedTime(new Date());
                elecStationService.insertSelectiveReturnId(elecStation);
                elecStation.getElecStationId();
            }
            return TResponse.SUCCESS_DATA(elecStation.getElecStationId());
        } catch (Exception e) {
            logger.error("保存桩群失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 删除桩群电价
     *
     * @return
     */
    @RequestMapping(value = "/deleteStation", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteStation(Long elecStationId) {

        try {
            elecStationService.deleteStationAndPileGun(elecStationId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除电价失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 跳转电价设置页面
     *
     * @return
     */
    @RequestMapping(value = "/elecStationPrice/{elecStationId}", method = RequestMethod.GET)
    public String electricityPricePage(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/elecStationPrice";
    }


    /**
     * 返回桩群电价列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listElecStationPrice", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listElecStationPrice(ElecStationPriceSearch elecStationPriceSearchVo) {
        PageInfo<ElecStationPrice> pageInfo = elecStationPriceService.searchByCondition(elecStationPriceSearchVo);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出收费列表
     */
    @ResponseBody
    @RequestMapping(value = "/exportPrice", method = RequestMethod.GET)
    public TResponse exportPrice(ElecStationPriceSearch elecStationPriceSearchVo, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            ExportUtils.setDefaultPaging(elecStationPriceSearchVo);
            PageInfo<ElecStationPrice> pageInfo = elecStationPriceService.searchByCondition(elecStationPriceSearchVo);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("收费列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ElecStationPrice.class).sheet("收费列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出收费列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    /* *//**
     * 返回订单详情电价列表数据
     *
     * @return
     *//*
    @RequestMapping(value = "/listStationPrice", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listStationPrice() {
        PageInfo<ElecStationPrice> pageInfo = elecStationPriceService.searchByCondition(elecStationPriceSearchVo);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }
*/

    /**
     * 跳转编辑桩群电价
     *
     * @return
     */
    @RequestMapping(value = "/editElecStationPrice/{priceId}", method = RequestMethod.GET)
    public String editElecStationPrice(@PathVariable("priceId") Long priceId, Model model) {
        ElecStationPrice elecStationPrice = elecStationPriceService.selectByPrimaryKey(priceId);
        model.addAttribute("elecStationPrice", elecStationPrice);
        return "/templates/elec/editElecStationPrice";
    }

    /**
     * 跳转增加桩群电价
     *
     * @return
     */
    @RequestMapping(value = "/addElecStationPrice/{elecStationId}", method = RequestMethod.GET)
    public String addElecStationPrice(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/addElecStationPrice";
    }

    /**
     * 保存编辑桩群电价
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateElecStationPrice", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateElecStationPrice(ElecStationPrice elecStationPrice) {

        TenantUser user = ShiroUtils.getSessionUser();

        if (!BeanUtil.isValid(elecStationPrice.getElecPrice(),
                elecStationPrice.getServicePrice(),
                elecStationPrice.getBeginTime(), elecStationPrice.getEndTime())) {
            return TResponse.FAIL("请输入正确的参数");
        }

        try {
            SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");

            ArrayList<String> list = new ArrayList<>();
            ArrayList<String> listDate = new ArrayList<>();
            //list.add(format.format(elecStationPrice.getBeginTime()) + "-" + format.format(elecStationPrice.getEndTime()));
            list.add(elecStationPrice.getBeginTime() + "-" + elecStationPrice.getEndTime());
            List<ElecStationPrice> stationPriceList = new ArrayList<>();
            if (elecStationPrice.getPriceId() != null) {
                //todo 编辑是要把之前id所对应的时间删除掉
                ElecStationPrice price = elecStationPriceService.selectByPrimaryKey(elecStationPrice.getPriceId());
                stationPriceList = elecStationPriceService.listPriceByStationId(price.getElecStationId());
            } else {
                stationPriceList = elecStationPriceService.listPriceByStationId(elecStationPrice.getElecStationId());
            }

            if (stationPriceList != null) {
                for (ElecStationPrice stationPrice : stationPriceList) {
                    if (elecStationPrice.getPriceId() != null && stationPrice.getPriceId().equals(elecStationPrice.getPriceId())) {
                        continue;
                    }
                    //list.add(format.format(stationPrice.getBeginTime()) + "-" + format.format(stationPrice.getEndTime()));
                    listDate.add(stationPrice.getBeginDate() + "," + stationPrice.getEndDate());
                    list.add(stationPrice.getBeginTime() + "-" + stationPrice.getEndTime());
                }
            }
//            Boolean overlappTime = TimeUtil.isOverlappTime(list);
//            Boolean overlappDate = TimeUtil.isOverlappDate(listDate, elecStationPrice.getBeginDate(), elecStationPrice.getEndDate());
//            if (overlappDate == true) {
//                return TResponse.FAIL("时间重叠");
//            }
//            if (overlappDate == true && overlappTime == true) {
//                return TResponse.FAIL("时间重叠");
//            }
            elecStationPrice.setLastUpdatedBy(user.getLoginName());
            elecStationPrice.setLastUpdatedTime(new Date());
            elecStationPrice.setTenantCode(user.getTenantCode());
            if (elecStationPrice.getPriceId() == null) {
                ElecStationPriceExample priceExample = new ElecStationPriceExample();
                priceExample.createCriteria().andElecStationIdEqualTo(elecStationPrice.getElecStationId());
                List<ElecStationPrice> lstElecStationPrice = elecStationPriceService.selectByExample(priceExample);
                if (lstElecStationPrice.size() > 12) {
                    return TResponse.FAIL("一个充电站只有12个时间分段");
                } else {
                    elecStationPrice.setCreatedBy(user.getLoginName());
                    elecStationPrice.setCreatedTime(new Date());
                    elecStationPriceService.insertSelectiveReturnId(elecStationPrice);
                    saveHlhtStationPrice(elecStationPrice);
                }
            } else {
                elecStationPriceService.updateByPrimaryKeySelective(elecStationPrice);
            }
            //发送open 价格变化， 站点自动推送（京东定制）

            Map<String, Long> map = new HashMap<>();
            map.put("StationID", elecStationPrice.getElecStationId() == null ? stationPriceList.get(0).getElecStationId() : elecStationPrice.getElecStationId());
            ObjectMapper objectMapper = new ObjectMapper();
            String msg = objectMapper.writeValueAsString(map);
            mqProducer.send(MqConfig.NOTIFY_STATIONINFOS, msg);
            logger.error("站点价格变动mq发送:{}", msg);

            ElecStationPrice elecStationPrice1 = elecStationPriceService.selectByPrimaryKey(elecStationPrice.getPriceId());
            List<ElecPile> elecPiles = elecPileService.listByElecStationId(elecStationPrice1.getElecStationId());
            elecPiles.stream().forEach(elecPile -> {
                PriceReq priceReq = new PriceReq(elecPile.getElecPileId());
                String jsonString = JSON.toJSONString(priceReq);
                //下发电价
                mqProducer.sendEvcharge(RabbitListenerConstant.DOMAIN1_YL_CONTROLL_4F_04_QUEUE, jsonString);
                logger.info("电价下发成功，对应站点编号:{},json:{}", elecPile.getPileNo(), jsonString);
            });

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存电价失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    public TResponse saveHlhtStationPrice(ElecStationPrice elecStationPrice) {
        TenantUser user = ShiroUtils.getSessionUser();
        //找出与该运营商有关的反向互联关系
        HlhtTenantOpenExample hlhtTenantOpenExample = new HlhtTenantOpenExample();
        hlhtTenantOpenExample.createCriteria().andTenantCodeEqualTo(user.getTenantCode()).andHlhtTypeEqualTo("0");
        List<HlhtTenantOpen> hlhtTenantOpenList = hlhtTenantOpenService.selectByExample(hlhtTenantOpenExample);

        for (HlhtTenantOpen hlhtTenantOpen : hlhtTenantOpenList) {
            HlhtTenantOpenPriceExample hlhtTenantOpenPriceExample = new HlhtTenantOpenPriceExample();
            HlhtTenantOpenPriceExample.Criteria criteria = hlhtTenantOpenPriceExample.createCriteria()
                    .andTenantCodeEqualTo(hlhtTenantOpen.getTenantCode())
                    .andElecStationIdEqualTo(elecStationPrice.getElecStationId())
                    .andPriceIdEqualTo(elecStationPrice.getPriceId());
            if ("0".equals(hlhtTenantOpen.getHlhtOpenType())) {
                criteria.andHlhtTenantCodeEqualTo(hlhtTenantOpen.getHlhtTenantCode());
            }
            if ("1".equals(hlhtTenantOpen.getHlhtOpenType()) || "2".equals(hlhtTenantOpen.getHlhtOpenType())) {
                criteria.andHlhtOperatorIdEqualTo(hlhtTenantOpen.getHlhtOperatorId());
            }
            long count = hlhtTenantOpenPriceService.countByExample(hlhtTenantOpenPriceExample);
            if (count > 0) {
                continue;
            }
            HlhtTenantOpenPrice hlhtTenantOpenPrice = new HlhtTenantOpenPrice();
            hlhtTenantOpenPrice.setTenantCode(hlhtTenantOpen.getTenantCode());
            if ("0".equals(hlhtTenantOpen.getHlhtOpenType())) {
                hlhtTenantOpenPrice.setHlhtTenantCode(hlhtTenantOpen.getHlhtTenantCode());
            } else if ("1".equals(hlhtTenantOpen.getHlhtOpenType()) || "2".equals(hlhtTenantOpen.getHlhtOpenType())) {
                hlhtTenantOpenPrice.setHlhtOperatorId(hlhtTenantOpen.getHlhtOperatorId());
            }
            hlhtTenantOpenPrice.setPriceId(elecStationPrice.getPriceId());
            hlhtTenantOpenPrice.setElecStationId(elecStationPrice.getElecStationId());
            try {
                hlhtTenantOpenPriceService.insertSelective(hlhtTenantOpenPrice);
            } catch (Exception e) {
                logger.error("新增互联站点价格失败", e);
                return TResponse.FAIL("新增互联站点价格失败");
            }
        }
        return TResponse.SUCCESS();
    }


    /**
     * 删除桩群电价
     *
     * @return
     */
    @RequestMapping(value = "/deleteElecStationPrice", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteElecStationPrice(Long priceId) {
        try {
            elecStationPriceService.deleteByPrimaryKey(priceId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除电价失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转桩页面
     *
     * @return
     */
    @RequestMapping(value = "/pileListPage/{elecStationId}", method = RequestMethod.GET)
    public String pileListPage(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/elecPileByStation";
    }


    /**
     * 跳转增加桩页面
     *
     * @return
     */
    @RequestMapping(value = "/addElecPileByStation/{elecStationId}", method = RequestMethod.GET)
    public String addElecPileByStation(@PathVariable("elecStationId") Long elecStationId, Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<TenantManufacturer> tenantManufacturerList = tenantManufacturerService.selectByTenantCode(user.getTenantCode(), "1");
        model.addAttribute("tenantManufacturerList", tenantManufacturerList);
        ElecStation elecStation = elecStationService.selectByPrimaryKey(elecStationId);
        model.addAttribute("elecStation", elecStation);
        Tenant tenant = tenantService.selectByPrimaryKey(user.getTenantCode());
        model.addAttribute("tenant", tenant);
        return "/templates/elec/addElecPileByStation";
    }


    /**
     * 跳转优惠方案页面
     *
     * @return
     */
    @RequestMapping(value = "/jumpDiscountPolicyPage/{elecStationId}", method = RequestMethod.GET)
    public String jumpDiscountPolicyPage(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/discount/discountPolicy";
    }

    /**
     * 跳转设置出场方式页面
     *
     * @return
     */
    @RequestMapping(value = "/elecStationOut/{elecStationId}", method = RequestMethod.GET)
    public String elecStationOut(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        ElecStationOut elecStationOut = elecStationOutService.selectByPrimaryKey(elecStationId);
        model.addAttribute("elecStationOut", elecStationOut);
        model.addAttribute("uploadPath", upYunConfig.getDownloadRoot());
        return "/templates/elec/elecStationOut";
    }

    /**
     * 跳转分销商页面
     *
     * @return
     */
    @RequestMapping(value = "/tenantOperatorStation/{elecStationId}", method = RequestMethod.GET)
    public String tenantOperatorStation(@PathVariable("elecStationId") Long elecStationId, Model model) {
        model.addAttribute("elecStationId", elecStationId);
        return "/templates/elec/tenantOperatorStation";
    }

    /**
     * 返回分销商列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageTenantOperatorStation", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo pageTenantOperatorStation(BaseSearch baseSearch, Long elecStationId) {
        PageInfo<TenantOperatorStationVo> pageInfo = tenantOperatorStationService.pageTenantOperatorStation(baseSearch, elecStationId);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 保存分销商
     *
     * @return
     */
    @RequestMapping(value = "/saveTenantOperatorStation", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveTenantOperatorStation(String loginName, Long elecStationId) {
        try {
            TenantOperator tenantOperator = tenantOperatorService.selectByLoginName(loginName);
            if (tenantOperator == null) {
                return TResponse.FAIL("无该分销商账号，请重新添加");
            }
            TenantOperatorStationExample example = new TenantOperatorStationExample();
            example.createCriteria().andTenantOperatorCodeEqualTo(tenantOperator.getTenantOperatorCode()).andElecStationIdEqualTo(elecStationId);
            List<TenantOperatorStation> tenantOperatorStations = tenantOperatorStationService.selectByExample(example);
            if (!CollectionUtils.isEmpty(tenantOperatorStations)) {
                return TResponse.FAIL("该账号已存在，请重新添加");
            }
            TenantUser tenantUser = ShiroUtils.getSessionUser();
            TenantOperatorStation tenantOperatorStation = new TenantOperatorStation();
            tenantOperatorStation.setTenantOperatorCode(tenantOperator.getTenantOperatorCode());
            tenantOperatorStation.setTenantCode(tenantUser.getTenantCode());
            tenantOperatorStation.setElecStationId(elecStationId);
            tenantOperatorStation.setStatus("0");
            tenantOperatorStationService.insertSelective(tenantOperatorStation);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存分销商失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 删除分销商桩群关系
     *
     * @return
     */
    @RequestMapping(value = "/deleteTenantOperatorStation", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteTenantOperatorStation(Long operatorStationId) {

        try {
            tenantOperatorStationService.deleteByPrimaryKey(operatorStationId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除分销商桩群关系失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存/编辑出场方式
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateElecStationOut", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateElecStationOut(ElecStationOut elecStationOut,
                                                @RequestParam(value = "file1", required = false) MultipartFile file1,
                                                @RequestParam(value = "file2", required = false) MultipartFile file2,
                                                @RequestParam(value = "file3", required = false) MultipartFile file3) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (!BeanUtil.isValid(elecStationOut.getOutType(),
                elecStationOut.getPrinterType(),
                elecStationOut.getIsFreeParking(), elecStationOut.getIsNeedNumber())) {
            return TResponse.FAIL("请输入正确的参数");
        }
        try {

            if (file1.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file1);
                if (tResponse.getStatus() == 200) {
                    elecStationOut.setOutImage1((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (file2.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file2);
                if (tResponse.getStatus() == 200) {
                    elecStationOut.setOutImage2((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }
            if (file3.getSize() != 0) {
                TResponse tResponse = uploadImg.uploadImg(user.getTenantCode(), file3);
                if (tResponse.getStatus() == 200) {
                    elecStationOut.setOutImage3((String) tResponse.getData());
                } else {
                    return tResponse;
                }
            }

            ElecStationOut template = elecStationOutService.selectByPrimaryKey(elecStationOut.getElecStationId());
            if (template != null) {
                elecStationOutService.updateByPrimaryKeySelective(elecStationOut);
            } else {
                elecStationOut.setTenantCode(user.getTenantCode());
                elecStationOutService.insertSelective(elecStationOut);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存出场方式失败", e);
            return TResponse.FAIL("保存出场方式失败");
        }
    }


    /**
     * 通过读取文件并获取其width及height的方式，来判断判断当前文件是否图片，这是一种非常简单的方式。
     *
     * @param imageFile
     * @return
     */
    public static boolean isImage(File imageFile) {
        if (!imageFile.exists()) {
            return false;
        }
        Image img = null;
        try {
            img = ImageIO.read(imageFile);
            if (img == null || img.getWidth(null) <= 0 || img.getHeight(null) <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            img = null;
        }
    }


    /**
     * 返回桩群列表数据(用于查询不包括互联互通)
     *
     * @return
     */
    @RequestMapping(value = "listElecStationData", method = RequestMethod.GET)
    @ResponseBody
    public List<ElecStation> listElecStationData() {
        TenantUser sessionUser = ShiroUtils.getSessionUser();
        List<ElecStation> elecStations = new ArrayList<ElecStation>();
        if (sessionUser.getTenantOperatorCode() != null) {
            elecStations = elecStationService.listAllStationByTenantOperatorCode(sessionUser.getTenantOperatorCode());
        } else {
            elecStations = elecStationService.listAllStationByTenantCode(sessionUser.getTenantCode());
        }
        return elecStations;
    }


    /**
     * 设置桩群置顶信息
     * *
     *
     * @return
     */
    @RequestMapping(value = "updateForTop", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateForTop(Long elecStationId, String showPlaceTag) {
        try {
            if (StringUtils.isBlank(showPlaceTag)) {
                return TResponse.FAIL("请输入置顶提示");
            }

            if (showPlaceTag.length() > 6) {
                return TResponse.FAIL("置顶提示超过6位");
            }

            ElecStation elecStation = new ElecStation();
            elecStation.setElecStationId(elecStationId);
            elecStation.setShowPlaceType("1");
            elecStation.setShowPlaceTag(showPlaceTag);
            elecStationService.updateByPrimaryKeySelective(elecStation);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存桩群置顶信息失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 取消桩群置顶
     * *
     *
     * @return
     */
    @RequestMapping(value = "updateForNoTop", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateForNoTop(Long elecStationId) {
        try {
            elecStationService.updateForNoTop(elecStationId);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("取消桩群置顶失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转安全防控页面
     *
     * @return
     */
    @RequestMapping(value = "/securityPrevention", method = RequestMethod.GET)
    public String securityPrevention(Model model) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        TenantSetting tenantSetting = tenantSettingService.selectByPrimaryKey(tenantUser.getTenantCode());
        model.addAttribute("tenantSetting", tenantSetting);
        return "/templates/elec/securityPrevention";
    }


    /**
     * 保存/编辑 安全防控
     *
     * @return
     */
    @RequestMapping(value = "/saveOrUpdateSecurityPrevention", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveOrUpdateSecurityPrevention(String batteryList, String socList, String openChargeLimitSoc, String openChargeLimitBatteryTemp) {
        TenantUser user = ShiroUtils.getSessionUser();
        try {
            List<SecurityPrevention> batteryStationIdList = JSONObject.parseArray(batteryList, SecurityPrevention.class);
            List<SecurityPrevention> socStationIdList = JSONObject.parseArray(socList, SecurityPrevention.class);
            elecStationService.updateSecurityStationList(batteryStationIdList, socStationIdList, openChargeLimitSoc, openChargeLimitBatteryTemp, user.getTenantCode());
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存安全防控失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 获取安全防控桩群数据
     *
     * @return
     */
    @RequestMapping(value = "/listSecurityPrevention", method = RequestMethod.GET)
    @ResponseBody
    public TResponse listSecurityPrevention() {
        TenantUser user = ShiroUtils.getSessionUser();
        try {

            TenantSetting tenantSetting = tenantSettingService.selectByPrimaryKey(user.getTenantCode());

            List<ElecStation> elecStationList = elecStationService.listAllStationByTenantCode(user.getTenantCode());

            List<SecurityPrevention> batteryList = new LinkedList<SecurityPrevention>() {
            };
            List<SecurityPrevention> socList = new LinkedList<SecurityPrevention>() {
            };

            for (ElecStation elecStation : elecStationList) {

                int isBattery = 0;
                int isSoc = 0;

                Integer limitBatteryTemp = elecStation.getLimitBatteryTemp();
                Integer limitSoc = elecStation.getLimitSoc();


                for (int i = 0; i < batteryList.size(); i++) {
                    if (limitBatteryTemp == null) {
                        break;
                    } else if (batteryList.get(i).getTemp().equals(limitBatteryTemp.toString())) {
                        if (batteryList.get(i).getStationId() != null) {
                            batteryList.get(i).setStationId(batteryList.get(i).getStationId().concat("," + elecStation.getElecStationId().toString()));
                        } else {
                            batteryList.get(i).setStationId(elecStation.getElecStationId().toString());
                        }
                        batteryList.set(i, batteryList.get(i));
                        isBattery = 1;
                        break;
                    }

                }

                if (limitBatteryTemp != null && isBattery != 1) {
                    SecurityPrevention prevention = new SecurityPrevention();
                    prevention.setTemp(elecStation.getLimitBatteryTemp().toString());
                    prevention.setStationId(elecStation.getElecStationId().toString());
                    batteryList.add(prevention);
                }

                for (int i = 0; i < socList.size(); i++) {
                    if (limitSoc == null) {
                        break;
                    } else if (socList.get(i).getTemp().equals(limitSoc.toString())) {
                        if (socList.get(i).getStationId() != null) {
                            socList.get(i).setStationId(socList.get(i).getStationId().concat("," + elecStation.getElecStationId().toString()));
                        } else {
                            socList.get(i).setStationId(elecStation.getElecStationId().toString());
                        }
                        socList.set(i, socList.get(i));
                        isSoc = 1;
                        break;
                    }
                }

                if (limitSoc != null && isSoc != 1) {
                    SecurityPrevention prevention = new SecurityPrevention();
                    prevention.setTemp(elecStation.getLimitSoc().toString());
                    prevention.setStationId(elecStation.getElecStationId().toString());
                    socList.add(prevention);
                }


                if (CollectionUtils.isEmpty(batteryList)) {
                    if (elecStation.getLimitBatteryTemp() != null) {
                        SecurityPrevention securityPrevention = new SecurityPrevention();
                        securityPrevention.setTemp(elecStation.getLimitBatteryTemp().toString());
                        securityPrevention.setStationId((elecStation.getElecStationId().toString()));
                        batteryList.add(securityPrevention);
                    }
                }

                if (CollectionUtils.isEmpty(socList)) {
                    if (elecStation.getLimitSoc() != null) {
                        SecurityPrevention securityPrevention = new SecurityPrevention();
                        securityPrevention.setTemp(elecStation.getLimitSoc().toString());
                        securityPrevention.setStationId((elecStation.getElecStationId().toString()));
                        socList.add(securityPrevention);
                    }
                }

            }

            String batteryListJson = "";
            String socListJson = "";
            if (!CollectionUtils.isEmpty(batteryList)) {
                batteryListJson = JSONObject.toJSONString(batteryList);
            }
            if (!CollectionUtils.isEmpty(socList)) {
                socListJson = JSONObject.toJSONString(socList);
            }
            return TResponse.SUCCESS_DATA(new SecurityModelVo(batteryListJson, socListJson, tenantSetting.getOpenChargeLimitSoc(), tenantSetting.getOpenChargeLimitBatteryTemp()));
        } catch (Exception e) {
            logger.error("获取安全防控桩群数据失败", e);
            return TResponse.FAIL("操作失败");
        }
    }
}
